package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.user.wechatblacklist.WechatBlacklistPubIdDto;
import com.uzai.console.dto.user.wechatblacklist.WechatBlacklistPubQuery;
import com.uzai.console.entity.es.WechatBlacklistPub;
import com.uzai.console.entity.es.WechatBlacklistPubWhite;
import com.uzai.console.mapper.WechatUserMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.user.WechatBlacklistPubService;
import com.uzai.console.vo.user.wechatblacklist.WechatBlacklistPubInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class WechatBlacklistPubServiceImpl implements WechatBlacklistPubService {

    Logger logger = LoggerFactory.getLogger(WechatBlacklistPubServiceImpl.class);

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private UserService userService;


    /**
     * 查询全网黑名单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wechatBlacklistPubQuery
     * @return null
     */
    public Page<WechatBlacklistPubInfoVo> findWechatBlacklistPubList(WechatBlacklistPubQuery wechatBlacklistPubQuery){
        //新建返回到页面的LIST对象
        List<WechatBlacklistPubInfoVo> wechatBlacklistPubPageVoList = new ArrayList<>();
        //执行分页查询对象
        Page<WechatBlacklistPubInfoVo> page = new Page<>();
        wechatBlacklistPubQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //黑名单类型(0常规 1刷单 2同行 3店淘 4敲诈 5撸狗)
        if(wechatBlacklistPubQuery.getType() != null){
            boolQuery.must(QueryBuilders.termQuery("type", wechatBlacklistPubQuery.getType()));
        }

        //微信id
        if(StringUtils.isNotBlank(wechatBlacklistPubQuery.getWxid())) {
            boolQuery.must(QueryBuilders.termQuery("wxid", wechatBlacklistPubQuery.getWxid()));
        }

        //会员id
        if(wechatBlacklistPubQuery.getUserId() != null){
            WechatUser wechatUser = wechatUserMapper.selectById(wechatBlacklistPubQuery.getUserId(), wechatBlacklistPubQuery.getMerId());
            if(wechatUser != null){
                boolQuery.must(QueryBuilders.termQuery("wxid", wechatUser.getWxid()));
            }
        }

        //高亮字段
        String highlightField = null;

        //微信昵称
        if(StringUtils.isNotBlank(wechatBlacklistPubQuery.getNickName())){
            boolQuery.must(QueryBuilders.matchQuery("nickName", wechatBlacklistPubQuery.getNickName()));
            highlightField = "nickName";
        }

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, searchSourceBuilder, wechatBlacklistPubQuery.getSize(), wechatBlacklistPubQuery.getFromIndex(), null, null, highlightField, null);
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WechatBlacklistPub.class);
                if(wechatBlacklistPub != null){
                    WechatBlacklistPubInfoVo wechatBlacklistPubInfoVo = new WechatBlacklistPubInfoVo();
                    BeanUtils.copyProperties(wechatBlacklistPub, wechatBlacklistPubInfoVo);

                    //来源名称
                    if(wechatBlacklistPub.getSource() == 0){
                        wechatBlacklistPubInfoVo.setSourceName("运营商共享");
                    }else if(wechatBlacklistPub.getSource() == 1){
                        wechatBlacklistPubInfoVo.setSourceName("官方采集-免费");
                    }else if(wechatBlacklistPub.getSource() == 2){
                        wechatBlacklistPubInfoVo.setSourceName("收费名单");
                    }

                    //是否加入白名单
                    String white_id = wechatBlacklistPubQuery.getMerId() + "_" + wechatBlacklistPub.getWxid();
                    Map<String,Object> map_white = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, white_id, null);
                    if(map_white == null){
                        wechatBlacklistPubInfoVo.setWhiteStatus(0);  //未加入白名单
                    }else{
                        wechatBlacklistPubInfoVo.setWhiteStatus(1);  //已经加入白名单
                    }

                    //封装会员id
                    User user = userService.findUserInfoByWxid(wechatBlacklistPubQuery.getMerId(), wechatBlacklistPub.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
                    if(user != null){
                        wechatBlacklistPubInfoVo.setUserId(user.getId());
                    }

                    wechatBlacklistPubPageVoList.add(wechatBlacklistPubInfoVo);
                }
            }
        }

        //返回到页面分页对象
        page.setRecords(wechatBlacklistPubPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 加入白名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wechatBlacklistPubIdDto
     * @return null
     */
    @Transactional
    public void addWechatBlacklistPubWhite(WechatBlacklistPubIdDto wechatBlacklistPubIdDto){

        if(StringUtils.isBlank(wechatBlacklistPubIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wechatBlacklistPubIdDto.getId(), null);
        WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
        if(wechatBlacklistPub == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此全网黑名单不存在");
        }

        if(Tools.getLong(wechatBlacklistPub.getMerId()).longValue() == wechatBlacklistPubIdDto.getMerId().longValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能将自己共享的全网黑名单加入到白名单当中");
        }

        String white_id = wechatBlacklistPubIdDto.getMerId() + "_" + wechatBlacklistPub.getWxid();
        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, white_id, null);
        WechatBlacklistPubWhite wechatBlacklistPubWhite  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(white_map)), WechatBlacklistPubWhite.class);
        if(wechatBlacklistPubWhite != null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此全网黑名单已经存在白名单列表中");
        }

        //加入白名称
        wechatBlacklistPubWhite = new WechatBlacklistPubWhite();
        BeanUtils.copyProperties(wechatBlacklistPub, wechatBlacklistPubWhite);
        wechatBlacklistPubWhite.setId(white_id);
        wechatBlacklistPubWhite.setMerId(wechatBlacklistPubIdDto.getMerId());
        Integer now = DateUtil.getNowTime();
        wechatBlacklistPubWhite.setCreateTime(now);
        wechatBlacklistPubWhite.setUpdateTime(now);
        //增加到全网黑名单
        elasticsearchUtil.addData(wechatBlacklistPubWhite, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, white_id);

        try {
            //延迟0.5秒
            Thread.sleep(500);
        }catch (Exception e){

        }

    }

    /**
     * 删除白名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wechatBlacklistPubIdDto
     * @return null
     */
    @Transactional
    public void deleteWechatBlacklistPubWhite(WechatBlacklistPubIdDto wechatBlacklistPubIdDto){

        if(StringUtils.isBlank(wechatBlacklistPubIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wechatBlacklistPubIdDto.getId(), null);
        WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
        if(wechatBlacklistPub == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此全网黑名单不存在");
        }

        //是否加入白名单
        String white_id = wechatBlacklistPubIdDto.getMerId() + "_" + wechatBlacklistPub.getWxid();
        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, white_id, null);
        WechatBlacklistPubWhite wechatBlacklistPubWhite  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(white_map)), WechatBlacklistPubWhite.class);
        if(wechatBlacklistPubWhite == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此微信id不存在白名单列表中");
        }

        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, white_id);

        try {
            //延迟0.5秒
            Thread.sleep(500);
        }catch (Exception e){

        }
    }

}
